package com.wzqj.agent.app.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.wzqj.agent.app.login.controller.AuthRequiredController;
import com.wzqj.agent.app.user.domain.UserInfo;
import com.wzqj.agent.app.user.service.ApiUserService;
import com.wzqj.agent.common.ConfigHelper;
import com.wzqj.agent.common.JsonOutput;
import com.wzqj.agent.common.exception.BusinessErrorType;
import com.wzqj.agent.util.ValidateUtil;
import com.wzqj.wsp.upload.OssTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * Created by wanghao@weipass.cn on 2015/7/31.
 */
@Controller
@RequestMapping("/api/user")
public class ApiUserController extends AuthRequiredController{

    private static String extName = "gif,jpg,jpeg,png,bmp"; //扩展名

    private static final String ALIYUN_URL = ConfigHelper.getProperty("ALIYUN_URL");
    /**
     * 阿里云存储客户端
     */
    private OssTemplate ossTemplate = new OssTemplate();

    @Autowired
    private ApiUserService apiUserService;

    /**
     * 获取用户信息
     * @return
     */
    @RequestMapping("/getUserInfo")
    @ResponseBody
    public JSONObject getUserInfo(String phone) {

        JsonOutput output = new JsonOutput();
        if(!ValidateUtil.isMobile(phone)){
            output.setErrCode(BusinessErrorType.PARAM_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.PARAM_ERROR.getErrMsg());
            return output.toJSONObject();
        }
        UserInfo userInfo = apiUserService.getUserInfo(phone);
        if ( null == userInfo ){
            output.setErrCode(BusinessErrorType.USER_GETIFNO_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.USER_GETIFNO_ERROR.getErrMsg());
        } else {
            Object data = JSONObject.toJSON(userInfo);
            output.setData(data);
        }
        return output.toJSONObject();
    }

    /**
     * 修改用户头像
     * @return
     */
    @RequestMapping("/updateUserInfo")
    @ResponseBody
    public JSONObject updateUserInfo(String phone,String iconUrl) {

        JsonOutput output = new JsonOutput();
        if (!ValidateUtil.isMobile(phone) || !ValidateUtil.isIconUrl(iconUrl)){
            output.setErrCode(BusinessErrorType.PARAM_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.PARAM_ERROR.getErrMsg());
            return output.toJSONObject();
        }
        UserInfo userInfo = apiUserService.updateUserInfo(phone, iconUrl);
        if ( null == userInfo ){
            output.setErrCode(BusinessErrorType.USER_UPDATE_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.USER_UPDATE_ERROR.getErrMsg());
        } else {
            Object data = JSONObject.toJSON(userInfo);
            output.setData(data);
        }
        return output.toJSONObject();
    }

    /**
     * 上传图片
     * @param request
     * @param response
     * @return
     * @throws IllegalStateException
     * @throws IOException
     * @throws IOException
     */
    @RequestMapping("/upload"  )
    @ResponseBody
    public JSONObject upload(MultipartHttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException, IOException {

        JsonOutput output = new JsonOutput();
        MultipartFile mf = request.getFile("imgFile");
        String filename = mf.getOriginalFilename();
        byte[] buf = mf.getBytes();
        String fileExt = getExtensionName(filename);
        if (buf == null) {//文件不存在
            output.setErrCode(BusinessErrorType.UPLOAD_FILE_NULL_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.UPLOAD_FILE_NULL_ERROR.getErrMsg());
            return output.toJSONObject();
        }
        //文件类型不正确
        if(!Arrays.<String>asList(extName.split(",")).contains(fileExt.toLowerCase())){
            output.setErrCode(BusinessErrorType.UPLOAD_FILE_NULL_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.UPLOAD_FILE_NULL_ERROR.getErrMsg());
            return output.toJSONObject();
        }
        String resId = ossTemplate.putFile(filename, buf); //上传到资源服务器
        String imgUrl = ALIYUN_URL + resId;
        JSONObject data = new JSONObject();
        data.put("imgUrl", imgUrl);
        output.setData(data);
        output.setMsg("上传成功");
        return output.toJSONObject();
    }

    /**
     * 取文件的扩展名
     * @param fileName
     * @return
     */
    public static String getExtensionName(String fileName) {
        if (fileName == null || fileName.trim().length() == 0) {
            return null;
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

}
